<template>
  <el-select
    style="width: 100%"
    v-model="warehouseVal"
    clearable
    filterable
    :placeholder="placeholder"
    :multiple="multiple"
    v-bind="$attrs"
  >
    <el-option
      label="全选"
      value="all"
      v-if="multiple"
      @click.native="selectAll"
    ></el-option>
    <el-option
      v-for="item in warehouse"
      :key="item.value"
      :label="item.label"
      :value="item.value"
    />
  </el-select>
</template>

<script setup>
import { getWarehouseOptions } from "@/api/public";

const props = defineProps({
  modelValue: { type: [String, Number, Array], default: "" },
  multiple: { type: Boolean, default: false },
  placeholder: { type: String, default: "请选择仓库" },
});

const emit = defineEmits(["update:modelValue", "change"]);

const warehouse = ref([]);
const warehouseVal = ref();

onMounted(() => {
  getStorehouse();
});

watch(
  () => props.modelValue,
  (val) => {
    warehouseVal.value = val;
  }
);

watch(
  () => warehouseVal.value,
  (val) => {
    emit("update:modelValue", val);
    emit("change", val);
  }
);

const getStorehouse = async () => {
  try {
    const res = await getWarehouseOptions({
      status: 1,
    });
    warehouse.value = res.data;
  } catch (e) {
    console.error(e);
  }
};

//全选
const selectAll = (val) => {
  if (warehouseVal.value?.length < warehouse.value?.length) {
    warehouseVal.value = [];
    warehouse.value?.map((item) => {
      warehouseVal.value.push(item.value);
    });
    warehouseVal.value = warehouseVal.value?.filter((item) => item != "all");
  } else {
    // 取消全选
    warehouseVal.value = [];
  }
};
</script>
